package com.qipay.resource.service.impl;

import com.qipay.resource.service.ImageHandleService;
import net.coobird.thumbnailator.Thumbnails;
import org.apache.commons.lang3.StringUtils;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;
import org.springframework.util.Assert;

import java.io.*;

/**
 * Creator: Yao
 * Date:    2016/7/22
 * For:
 * Other:
 */
@Component
public class ImageHandleServiceImpl implements ImageHandleService {

    final Logger logger = LoggerFactory.getLogger(ImageHandleServiceImpl.class);

    @Override
    public void thumbnail(String srcPath, String destPath) throws IOException {

        Assert.isTrue(StringUtils.isNoneBlank(srcPath) && StringUtils.isNoneBlank(destPath),"src or dest path is null");

        try {
            Thumbnails.of(srcPath).size(400, 400).toFile(destPath);
        } catch (Exception e) {
            e.printStackTrace();
            copy(srcPath, destPath);
        }
    }

    @Override
    public void thumbnail(String srcPath, String destPath, int width, int height) throws IOException {

        Assert.isTrue(StringUtils.isNoneBlank(srcPath) && StringUtils.isNoneBlank(destPath),"path mush input");
        Assert.isTrue(width > 0 && height > 0,"width,height value is not right");

        try {
            Thumbnails.of(srcPath).size(width, height).toFile(destPath);
        } catch (Exception e) {
            e.printStackTrace();
            copy(srcPath, destPath);
        }
    }

    private void copy(String srcPath, String destPath) {

        File srcFile = new File(srcPath);
        Assert.isTrue(srcFile.exists());

        File destFile = new File(destPath);
        destFile.getParentFile().mkdirs();

        FileInputStream is = null;
        FileOutputStream os = null;
        try {
            is = new FileInputStream(srcFile);
            os = new FileOutputStream(destFile);
            IOUtils.copy(is, os);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            IOUtils.closeQuietly(is);
            IOUtils.closeQuietly(os);
        }
    }
}
